package com.qf.service.impl;

import cn.hutool.core.util.IdUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.entity.TlAdmin;
import com.qf.mapper.AdminMapper;
import com.qf.service.AdminService;
import com.qf.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, TlAdmin> implements AdminService {
    @Autowired
    QiNiuTools qiNiuTools;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public ResultMsg adminlogin(String name,String pass) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("admin_name",name);
        queryWrapper.eq("admin_pass",pass);
        TlAdmin one = super.getOne(queryWrapper);
        if (one==null)
            return ResultMsg.ERROR(Mycode.LOGIN_ERRO);
        String s = IdUtil.createSnowflake(0, 0).nextIdStr();
        String token = TokenTools.create(name, pass);
        redisTemplate.boundValueOps(RedisKey.LOGIN_USER+s).set(token);
        return ResultMsg.SUCCESS(s);
    }

    @Override
    public ResultMsg updateadmin(TlAdmin admin) {
        TlAdmin byId = super.getById(admin.getAdminId());
        if (byId.getAdminPass().equals(admin.getAdminPass())){
            boolean b = super.saveOrUpdate(admin);
            if (b)
                return ResultMsg.SUCCESS();
        }
        boolean b = super.saveOrUpdate(admin);
        if (b)
            return ResultMsg.ERROR(666);
        return ResultMsg.ERROR(Mycode.UPDATE_ERRO);
    }

    @Override
    public ResultMsg uppic(MultipartFile pic) {
        String upload = qiNiuTools.upload(pic);
        return ResultMsg.SUCCESS(upload);
    }

    @Override
    public ResultMsg findadmin(HttpServletRequest request) {
        String adtoken = request.getHeader("token");
        String s = (String) redisTemplate.boundValueOps(RedisKey.LOGIN_USER+adtoken).get();
        List<String> audience = JWT.decode(s).getAudience();
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("admin_name",audience.get(0));
        TlAdmin one = super.getOne(queryWrapper);
        if (one==null)
            return  ResultMsg.ERROR(Mycode.LOGIN_ERRO);
        return ResultMsg.SUCCESS(one);
    }


}
